/*******************************************************************************
 * SDP Project AUT 2012
 * 
 *                ***********Driving Assistant************
 * Team:
 * Gisela, Deidre, Brijesh, Robert
 * 
 * This class keeps a log of the systems exceptions in a text file (logFile.txt)
 * Limited entries to file = 1000.
 * 
 * @version 1.0
 * 
 * Copyright (c) 2012 by DrivingAssistant Team, Inc., All Rights Reserved.
 * 
 ******************************************************************************/

package com.drivingAssistant.model;

//import UserInterface.CardTable;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Class ExceptionLogger creates a log of exceptions which could be used to 
 * help with future maintenance.
 */
public class ExceptionLogger {
    
    // constants
    private final static String DEFAULT_LOG = "EMPTY LOG ENTRY";
    private File LOG_FILE = null;
    
    // variables
    private String logText = "";
    private String currentLogText = "";
    private String todaysDate = "";
    private long numberLogs;
    
    Calendar currentDate = null;
    SimpleDateFormat formatter = null;
    
    // Input and output streams     
    protected FileInputStream fileInput = null;
    protected DataInputStream dataInput = null;
    protected FileOutputStream output = null; 
    protected BufferedReader buffReader = null;
    protected PrintStream printStream = null;
    
    /**
     * Constructor to create ExceptionLogger objects. 
     */
    public ExceptionLogger() {
        checkFileExists();
        setDate();
    }
    
    /**
     * Add the exception string and check if empty.
     * Increment number of logs so far.
     * 
     * @param log which is the string exception
     */
    public void addLog(String log) {
        this.logText += log;
        try {
            if (logText.isEmpty()) {
                logText = DEFAULT_LOG;
            }
            checkFileExists();
            updateFile();
            if (numberLogs > 1000) {
                resetLogFile();
            }
        } catch (NullPointerException npe) {
            // Exception caught leave empty for now
        }

    }
    
    /**
     * check file exists else create the file
     */
    private void checkFileExists() {
        if (LOG_FILE != null) {
            loadFile();
        } else {
            LOG_FILE = new File("file/logFile.txt");
        }
    }
    
    /**
     * set up the date formatted
     */
    private void setDate() {
        currentDate = Calendar.getInstance();
        formatter = new SimpleDateFormat("yyyy/MMM/dd HH:mm:ss");
        todaysDate = formatter.format(currentDate.getTime());
    }
    
    /**
     * Reset file
     */
    private void resetLogFile() {
        this.LOG_FILE.delete();
        updateFile();
    }
    
    /**
     * Load the file
     */
    private void loadFile() {
        try {
            if (LOG_FILE.exists()) {
                fileInput = new FileInputStream(LOG_FILE);
                dataInput = new DataInputStream(fileInput);
                buffReader = new BufferedReader(new InputStreamReader(dataInput));
                String tempString = "";
                while ((tempString = buffReader.readLine()) != null) {
                    currentLogText += "\n" + tempString;
                }
            } else {
                currentLogText += "Unable to load file...";
            }
        } catch (IOException ex) {
            Logger.getLogger(ExceptionLogger.class.getName())
                    .log(Level.SEVERE, null, ex);
        } finally {
            try {
                if (fileInput != null) {
                    fileInput.close();
                }
                if (dataInput != null) {
                    dataInput.close();
                }
                if (buffReader != null) {
                    buffReader.close();
                }
            } catch (IOException ex) {
                currentLogText += "Unable to close file...";
            }

        }
    }
    
    /**
     * Update and write to the file.
     */
    private void updateFile() {
        try {
            if(LOG_FILE != null) {
                output = new FileOutputStream(LOG_FILE);
                printStream = new PrintStream(output);
                printStream.print(this.currentLogText);
                printStream.println();
                printStream.print(todaysDate + logText);
                printStream.println(); // blank line
                numberLogs = LOG_FILE.length();
                currentLogText = ""; // reset strings
                logText = "";
            } else {
                logText += "File has been deleted, now creating new file..."; 
                LOG_FILE = new File("file/logFile.txt");
                addLog(logText);
                numberLogs = LOG_FILE.length();
            }
        } catch (IOException ex) {
            Logger.getLogger(ExceptionLogger.class.getName())
                    .log(Level.SEVERE, null, ex);
        } finally {
            try {
                if (output != null && printStream != null) { // take care of streams
                    output.flush();
                    output.close();
                    printStream.close();
                }
            } catch (IOException ex) {
                Logger.getLogger(ExceptionLogger.class.getName())
                        .log(Level.SEVERE, null, ex);
            }
        }
    } // end updateFile()
    
} // end ExceptionLogger
